<template>
    <div id="mySwiper">
        <ul :style="{
            width: 100 * banners.length + '%',
            left: left,
            transition: transition
        }">
            <li v-for="(item, i) in banners" :key="i" :style="{
                width: 100/banners.length + '%'
            }" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" >
                <img :src="item.picUrl" alt="">
            </li>
        </ul>
    </div>
</template> 
 
<script>
let setInt
export default {
    name: '',
    props: {
        banners: {
            type: Array,
            default: () => {
                return []
            }
        },

        autoplay: {
            default: false
        }
    },
    data() { 
        return {
            left: '-100%',
            transition: 'none',
            direction: 'left',
            startX: 0
        }
    },
    created() {
        if(this.autoplay !== false) {
            setInt = setInterval(() => {
                this.touchEnd()
            }, 3000);
        }
       
    },
    methods:{
        touchStart(e) {
            clearInterval(setInt)
            this.startX = e.touches[0].pageX
        },

        touchMove(e) {
            let moveX = e.touches[0].pageX - this.startX

            if(moveX > 0) {
                this.direction = 'right'
            } else if(moveX < 0) {
                this.direction = 'left'
            }
        },

        touchEnd() {
            let timer
            this.transition = "left .5s linear"
            clearTimeout(timer)
            if(this.direction == 'left') {
                this.left = '-200%'
                timer = setTimeout(() => {
                    let item = this.banners.shift()
                    this.banners.push(item)
                    this.transition = "none"
                    this.left = '-100%'
                }, 500);
            } else if(this.direction == 'right') {
                this.left = '0%'
                timer = setTimeout(() => {
                    let item = this.banners.pop()
                    this.banners.unshift(item)
                    this.transition = "none"
                    this.left = '-100%'
                }, 500);
            }
        }

    }, 
}
</script>

<style scoped lang="scss">
    
</style>